﻿using Fly.Domain.Infrastructure;
using Fly.Domain.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Fly.Domain.Extension;
using Fly.Domain.Email;
using Fly.Domain.Configuration;

namespace Fly.Domain.Services
{
    public class UserService : BaseService<User, int>
    {
        /// <summary>
        /// 发送激活邮件
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public Response SendActivateEmail(string email)
        {
            var response = new Response();
            var user = DbBase.Query<User>().SingleOrDefault(p => p.Email == email);
            if (user == null)
            {
                response.Message = "发送失败,请重新登录后重试.";
                return response;
            }
            user.EmailConfirmToken = (email + DateTime.Now.Ticks).ToMd5().ToLower();
            var result = DbBase.UpdateMany<User>().OnlyFields(p => p.EmailConfirmToken).Where(p => p.Id == user.Id).Execute(user);
            if (IsUpdateSuccess(result))
            {
                var url = WebConfigApplicationSettings.GetAppSettings("Domain", "http://fly.zhengjinfan.cn/") + "emailvalidate/" + user.EmailConfirmToken;
                var body = new StringBuilder();
                body.Append("您好：" + user.Nickname + "<br/>");
                body.Append("<p>请点击链接激活您的邮箱：");//target=\"_blank\"
                body.Append("<a href=\"" + url + "\"  >" + url + "</a>");
                body.Append("</p>");

                //发送邮件
                new SmtpService().SendMail(email, "(勿回)Fly社区激活邮件", body.ToString());

                response.IsSuccess = true;
                response.Message = "发送成功,请注意查看邮件.";
                return response;
            }

            response.Message = "发送失败,请重新登录后重试.";
            return response;
        }

        /// <summary>
        /// 验证邮箱
        /// </summary>
        /// <param name="token">token</param>
        /// <returns></returns>
        public Response EmailValidate(string token)
        {
            var response = new Response();
            if (string.IsNullOrEmpty(token))
            {
                response.Message = "验证失败：信息无效，请登录重新发送激活链接.";
                return response;
            }
            var user = DbBase.Query<User>().SingleOrDefault(p => p.EmailConfirmToken == token);
            if (user == null)
            {
                response.Message = "验证失败：信息无效，请登录重新发送激活链接.";
                return response;
            }
            user.EmailConfirmed = true;
            user.EmailIsUpdate = false;
            var result = DbBase.Update(user);
            if (IsUpdateSuccess(result))
            {
                response.IsSuccess = true;
                response.Message = "邮箱验证成功，帐号可以正常使用啦.";
                return response;
            }

            response.Message = "验证失败：信息无效，请登录重新发送激活链接.";
            return response;
        }

        /// <summary>
        /// 更新用户头像
        /// </summary>
        /// <param name="headPortrait"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public void UpdateHeadPortrait(string headPortrait, int userId)
        {
            var response = new Response();

            DbBase.UpdateMany<User>().OnlyFields(p => p.HeadPortrait).Where(p => p.Id == userId).Execute(new User
            {
                HeadPortrait = headPortrait
            });
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public User Login(string email)
        {
            return DbBase.Query<User>().SingleOrDefault(p => p.Email == email);
        }
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns></returns>
        public User GetUserInfo(int userId)
        {
            return DbBase.SingleOrDefaultById<User>(userId);
        }
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="nickname">昵称</param>
        /// <returns></returns>
        public User GetUserByNickname(string nickname)
        {
            return DbBase.Query<User>().SingleOrDefault(p => p.Nickname == nickname);
        }
        /// <summary>
        /// 更新用户信息
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public Response UpdateUser(User entity)
        {
            if (entity == null)
                throw new ArgumentNullException(nameof(entity));

            ThrowExceptionIfEntityIsInvalid(entity);

            var response = new Response();
            var result = DbBase.Update(entity);
            if (IsInsertSuccess(result))
            {
                response.IsSuccess = true;
                response.Message = "更新成功！";
                return response;
            }

            response.Message = "更新失败，请检查！";
            return response;
        }

        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public Response Register(User entity)
        {
            if (entity == null)
                throw new ArgumentNullException(nameof(entity));

            ThrowExceptionIfEntityIsInvalid(entity);

            var response = new Response();
            var result = DbBase.Insert(entity);
            if (IsInsertSuccess(result))
            {
                response.IsSuccess = true;
                response.Message = "注册成功！";
                return response;
            }

            response.Message = "注册失败，请检查！";
            return response;
        }
        /// <summary>
        /// 检查邮箱是否已存在
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public bool CheckEmailIsExists(string email, int? userId = null)
        {
            if (userId != null)
                return DbBase.Query<User>().Any(p => p.Email == email && p.Id != userId);
            return DbBase.Query<User>().Any(p => p.Email == email);
        }
        /// <summary>
        /// 检查昵称是否已存在
        /// </summary>
        /// <param name="nickname"></param>
        /// <returns></returns>
        public bool CheckNicknameIsExists(string nickname, int? userId = null)
        {
            if (userId != null)
                return DbBase.Query<User>().Any(p => p.Nickname == nickname && p.Id != userId);
            return DbBase.Query<User>().Any(p => p.Nickname == nickname);
        }
    }
}
